// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace SnapObjects.Data
{
    internal class CommandBuilderContext
    {
        private readonly IList<IAdoDbParameter> _parameters;
        private readonly IList<ResultSetMapping> _resultSetMappings;

        public CommandBuilderContext()
        {
            this.SqlBuilder = new StringBuilder();
            _parameters = new List<IAdoDbParameter>();
            _resultSetMappings = new List<ResultSetMapping>();
        }

        public void Reset()
        {
            this.SqlBuilder.Clear();
            _parameters.Clear();
            _resultSetMappings.Clear();
        }

        public StringBuilder SqlBuilder { get; }

        public IReadOnlyList<IAdoDbParameter> AdoDbParameters =>
                        (IReadOnlyList<IAdoDbParameter>)_parameters;

        public IReadOnlyList<ResultSetMapping> ResultSetMappings =>
                        (IReadOnlyList<ResultSetMapping>)_resultSetMappings;

        public ResultSetMapping FirstOrDefaultResultSetMapping =>
                        _resultSetMappings.Count > 0 ? _resultSetMappings[0] : ResultSetMapping.NoResultSet;

        public void AddParameter(string name, object value, Type clrType,
            ParameterDirection diretion = ParameterDirection.Input)
        {
            _parameters.Add(new AdoDbParameter(name, value, clrType, diretion));
        }

        public void AddParameter(string name,
            object value,
            Type clrType,
            ParameterDirection direction,
            string typeName,
            ValueConverter valueConverter)
        {
            var adoDbParameter = new AdoDbParameter(name, value, clrType, direction, typeName, 0, 0, -1);

            adoDbParameter.ValueConverter = valueConverter;

            _parameters.Add(adoDbParameter);
        }

        public void AddResultSetMapping(ResultSetMapping resultSetMapping)
        {
            _resultSetMappings.Add(resultSetMapping);
        }
    }
}
